import {createAsyncThunk, createSlice, PayloadAction} from "@reduxjs/toolkit";
import axios, {Home} from "../../utils";

interface IHomeDataResp {
  success: boolean,
  data: IHomeData
}

interface IHomeData {
  topicList: Topic[],
  articleList: Article[],
  recommendList: Recommend[],
  writers: IWriter[],
}

interface BaseInfo {
  id: string,
  imgUrl: string
}

interface IWriter {
  id: string,
  name: string,
  avatar: string
}


export interface Topic extends BaseInfo {
  title: string
}

interface Article extends BaseInfo {
  title: string
  desc: string
}

type Recommend = BaseInfo

// 获取主页数据到redux
export const getHomeData = createAsyncThunk(
  "homeData",
  async () => {
    const {data} = await axios.get<IHomeDataResp>(Home.DATA);
    return data.data
  }
)

export const topicSlice = createSlice({
  name: "topic",
  initialState: [] as Topic[],
  reducers: {},
  extraReducers: {
    [getHomeData.fulfilled.type]: (state, action: PayloadAction<IHomeData>) => action.payload.topicList
  }
})

export const articleSlice = createSlice({
  name: "article",
  initialState: [] as Article[],
  reducers: {
    // 加载更多
    loadMore: state => {
      state.push(...state);  // 这里有问题，key值重复，懒得改了
    }
  },
  extraReducers: {
    [getHomeData.fulfilled.type]: (state, action: PayloadAction<IHomeData>) => action.payload.articleList
  }
})

export const recommendSlice = createSlice({
  name: "recommend",
  initialState: [] as Recommend[],
  reducers: {},
  extraReducers: {
    [getHomeData.fulfilled.type]: (state, action: PayloadAction<IHomeData>) => action.payload.recommendList
  }
})

export const writerSlice = createSlice({
  name: "writer",
  initialState: [] as IWriter[],
  reducers:{},
  extraReducers: {
    [getHomeData.fulfilled.type]: (state, action: PayloadAction<IHomeData>) => action.payload.writers
  }
})

export const {loadMore} = articleSlice.actions
